const { 
  Connection, 
  Keypair, 
  PublicKey, 
  Transaction,
  sendAndConfirmTransaction,
  LAMPORTS_PER_SOL 
} = require('@solana/web3.js');
const {
  getAssociatedTokenAddress,
  createAssociatedTokenAccountInstruction,
  createTransferInstruction,
  getAccount,
  TOKEN_PROGRAM_ID,
  ASSOCIATED_TOKEN_PROGRAM_ID
} = require('@solana/spl-token');

// 配置
const DEVNET_RPC = 'https://api.devnet.solana.com';
const TOKEN_MINT = '7uTpUhobocigTVnxF7Z8w5iGgEnxqn9gCm5Bazk5mW8i'; // 您创建的代币
const SELLER_ADDRESS = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac'; // 代币创建者（卖家）
const BUYER_ADDRESS = '3N5UkPsssdMAjjyF5vje7k5pgJoYPsBouPBLbtZaxa2U'; // 买家

// 模拟交易参数
const TRANSACTIONS = [
  { solAmount: 0.1, tokenAmount: 1000 }, // 买入1000代币，花费0.1 SOL
  { solAmount: 0.2, tokenAmount: 2000 }, // 买入2000代币，花费0.2 SOL
  { solAmount: 0.05, tokenAmount: 500 }, // 买入500代币，花费0.05 SOL
  { solAmount: 0.3, tokenAmount: 3000 }, // 买入3000代币，花费0.3 SOL
  { solAmount: 0.15, tokenAmount: 1500 }, // 买入1500代币，花费0.15 SOL
];

async function simulateTokenPurchases() {
  console.log('🚀 开始模拟代币购买交易...\n');
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  const tokenMint = new PublicKey(TOKEN_MINT);
  const seller = new PublicKey(SELLER_ADDRESS);
  const buyer = new PublicKey(BUYER_ADDRESS);
  
  // 注意：在实际应用中，您需要买家的私钥来签署交易
  // 这里我们只是模拟交易结构，实际执行需要真实的密钥
  
  console.log(`📊 代币信息:`);
  console.log(`- Mint 地址: ${TOKEN_MINT}`);
  console.log(`- 卖家地址: ${SELLER_ADDRESS}`);
  console.log(`- 买家地址: ${BUYER_ADDRESS}\n`);
  
  // 获取卖家和买家的代币账户
  const sellerTokenAccount = await getAssociatedTokenAddress(tokenMint, seller);
  const buyerTokenAccount = await getAssociatedTokenAddress(tokenMint, buyer);
  
  console.log(`💰 代币账户信息:`);
  console.log(`- 卖家代币账户: ${sellerTokenAccount.toString()}`);
  console.log(`- 买家代币账户: ${buyerTokenAccount.toString()}\n`);
  
  // 检查买家代币账户是否存在
  let buyerAccountExists = false;
  try {
    await getAccount(connection, buyerTokenAccount);
    buyerAccountExists = true;
    console.log('✅ 买家代币账户已存在');
  } catch (error) {
    console.log('❌ 买家代币账户不存在，需要创建');
  }
  
  // 模拟交易
  for (let i = 0; i < TRANSACTIONS.length; i++) {
    const { solAmount, tokenAmount } = TRANSACTIONS[i];
    
    console.log(`\n🔄 交易 ${i + 1}:`);
    console.log(`- 购买数量: ${tokenAmount} 代币`);
    console.log(`- 支付金额: ${solAmount} SOL`);
    
    try {
      const transaction = new Transaction();
      
      // 如果是第一次交易且买家账户不存在，创建关联代币账户
      if (i === 0 && !buyerAccountExists) {
        console.log('📝 添加创建买家代币账户指令...');
        transaction.add(
          createAssociatedTokenAccountInstruction(
            buyer, // payer
            buyerTokenAccount, // associatedToken
            buyer, // owner
            tokenMint // mint
          )
        );
      }
      
      // 添加代币转账指令（从卖家到买家）
      console.log('📝 添加代币转账指令...');
      const tokenAmountWithDecimals = tokenAmount * Math.pow(10, 9); // 9位小数
      transaction.add(
        createTransferInstruction(
          sellerTokenAccount, // source
          buyerTokenAccount, // destination
          seller, // owner
          tokenAmountWithDecimals // amount
        )
      );
      
      // 添加SOL转账指令（从买家到卖家）
      console.log('📝 添加SOL转账指令...');
      const { SystemProgram } = require('@solana/web3.js');
      transaction.add(
        SystemProgram.transfer({
          fromPubkey: buyer,
          toPubkey: seller,
          lamports: solAmount * LAMPORTS_PER_SOL
        })
      );
      
      // 获取最新区块哈希
      const { blockhash } = await connection.getLatestBlockhash();
      transaction.recentBlockhash = blockhash;
      transaction.feePayer = buyer;
      
      // 序列化交易（模拟签名和发送）
      const serializedTransaction = transaction.serialize({ 
        requireAllSignatures: false 
      }).toString('base64');
      
      console.log('✅ 交易已准备完成');
      console.log(`📋 交易大小: ${serializedTransaction.length} 字符`);
      
      // 模拟交易确认
      console.log('⏳ 模拟交易确认中...');
      await new Promise(resolve => setTimeout(resolve, 1000));
      console.log('✅ 交易模拟成功');
      
      // 显示交易摘要
      console.log(`📊 交易摘要:`);
      console.log(`  - 代币转移: ${tokenAmount} 代币 ${SELLER_ADDRESS.slice(0,8)}... → ${BUYER_ADDRESS.slice(0,8)}...`);
      console.log(`  - SOL 支付: ${solAmount} SOL ${BUYER_ADDRESS.slice(0,8)}... → ${SELLER_ADDRESS.slice(0,8)}...`);
      
    } catch (error) {
      console.error(`❌ 交易 ${i + 1} 失败:`, error.message);
    }
    
    // 添加延迟
    if (i < TRANSACTIONS.length - 1) {
      console.log('⏳ 等待2秒后执行下一个交易...');
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
  
  // 计算总交易统计
  const totalSOL = TRANSACTIONS.reduce((sum, tx) => sum + tx.solAmount, 0);
  const totalTokens = TRANSACTIONS.reduce((sum, tx) => sum + tx.tokenAmount, 0);
  
  console.log(`\n📈 交易统计:`);
  console.log(`- 总交易数: ${TRANSACTIONS.length}`);
  console.log(`- 总购买代币: ${totalTokens.toLocaleString()}`);
  console.log(`- 总支付SOL: ${totalSOL} SOL`);
  console.log(`- 平均价格: ${(totalSOL / totalTokens).toFixed(6)} SOL/代币`);
  
  return {
    totalTransactions: TRANSACTIONS.length,
    totalTokens,
    totalSOL,
    averagePrice: totalSOL / totalTokens
  };
}

// 创建实际可执行的交易函数（需要买家私钥）
async function executeRealTransaction(buyerKeypair, transactionIndex = 0) {
  console.log('\n🎯 执行真实交易...');
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  const tokenMint = new PublicKey(TOKEN_MINT);
  const seller = new PublicKey(SELLER_ADDRESS);
  const buyer = buyerKeypair.publicKey;
  
  const { solAmount, tokenAmount } = TRANSACTIONS[transactionIndex];
  
  try {
    const transaction = new Transaction();
    
    // 获取代币账户
    const sellerTokenAccount = await getAssociatedTokenAddress(tokenMint, seller);
    const buyerTokenAccount = await getAssociatedTokenAddress(tokenMint, buyer);
    
    // 检查买家代币账户是否存在
    let buyerAccountExists = false;
    try {
      await getAccount(connection, buyerTokenAccount);
      buyerAccountExists = true;
    } catch (error) {
      // 账户不存在，需要创建
    }
    
    // 如果需要，创建买家的代币账户
    if (!buyerAccountExists) {
      transaction.add(
        createAssociatedTokenAccountInstruction(
          buyer,
          buyerTokenAccount,
          buyer,
          tokenMint
        )
      );
    }
    
    // 添加代币转账（需要卖家签署，这里只是示例）
    const tokenAmountWithDecimals = tokenAmount * Math.pow(10, 9);
    transaction.add(
      createTransferInstruction(
        sellerTokenAccount,
        buyerTokenAccount,
        seller, // 注意：这需要卖家的签名
        tokenAmountWithDecimals
      )
    );
    
    // 添加SOL支付
    const { SystemProgram } = require('@solana/web3.js');
    transaction.add(
      SystemProgram.transfer({
        fromPubkey: buyer,
        toPubkey: seller,
        lamports: solAmount * LAMPORTS_PER_SOL
      })
    );
    
    // 设置交易参数
    const { blockhash } = await connection.getLatestBlockhash();
    transaction.recentBlockhash = blockhash;
    transaction.feePayer = buyer;
    
    console.log('⚠️  注意：此交易需要卖家也签署才能执行');
    console.log('📋 交易已准备，等待签署...');
    
    // 返回准备好的交易
    return {
      transaction,
      needsSellerSignature: true,
      summary: {
        tokenAmount,
        solAmount,
        buyer: buyer.toString(),
        seller: seller.toString()
      }
    };
    
  } catch (error) {
    console.error('❌ 创建交易失败:', error);
    throw error;
  }
}

// 主函数
if (require.main === module) {
  simulateTokenPurchases()
    .then((stats) => {
      console.log('\n🎉 模拟交易完成！');
      console.log('\n💡 提示：');
      console.log('- 这些是模拟交易，展示了交易结构');
      console.log('- 要执行真实交易，需要买家和卖家的私钥');
      console.log('- 在实际应用中，通常通过DEX或AMM进行代币交易');
    })
    .catch(error => {
      console.error('❌ 错误:', error);
    });
}

module.exports = { 
  simulateTokenPurchases, 
  executeRealTransaction 
};
